/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-6-21 下午4:23:07
 */
package com.absir.android.view;

import java.lang.reflect.Field;

import android.view.View;

import com.absir.android.view.annotation.InjectBinder;
import com.absir.android.view.annotation.InjectView;
import com.absir.android.view.listener.Listener;
import com.absir.core.kernel.KernelLang.CauseRuntimeException;
import com.absir.core.kernel.KernelObject;

/**
 * @author absir
 * 
 */
public class InjectViewField extends InjectViewAbstract {

	/** field */
	private Field field;

	/** injectView */
	private InjectView injectView;

	/**
	 * @param field
	 * @param injectView
	 */
	public InjectViewField(Field field, InjectView injectView) {
		field.setAccessible(true);
		this.field = field;
		this.injectView = injectView;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.android.view.InjectViewAbstract#injectExcutor(com.absir.android
	 * .view.InjectExcutorObject)
	 */
	@Override
	public void injectExcutor(InjectExcutorObject<Object> injectExcutorObject) {
		// TODO Auto-generated method stub
		View value = injectExcutorObject.findViewById(injectView.value(), "id", field.getName());
		if (value != null && field.getType().isAssignableFrom(value.getClass())) {
			try {
				field.set(injectExcutorObject.getObject(), value);
				for (InjectBinder injectBinder : injectView.binders()) {
					Object target = KernelObject.expressGetter(injectExcutorObject.getObject(), injectBinder.target());
					if (target != null) {
						for (Class<? extends Listener> listenerClass : injectBinder.listeners()) {
							Listener listener = listenerClass.newInstance();
							listener.listener(value, injectExcutorObject.getTarget(target), injectBinder.method());
						}
					}
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				throw new CauseRuntimeException(e);
			}
		}
	}
}
